package io.webfolder.cdp.session;

import java.util.Map;

import io.webfolder.cdp.event.Events;
import io.webfolder.cdp.event.target.DetachedFromTarget;
import io.webfolder.cdp.event.target.TargetDestroyed;
import io.webfolder.cdp.listener.EventListener;

class TargetListener implements EventListener {

	private Map<String, Session> sessions;

	TargetListener(Map<String, Session> sessions) {
		this.sessions = sessions;
	}

	@Override
	public void onEvent(Events event, Object value) {
		switch (event) {
		case TargetTargetDestroyed:
			TargetDestroyed destroyed = (TargetDestroyed) value;
			for (Session next : sessions.values()) {
				if (destroyed.getTargetId().equals(next.getTargetId())) {
					if (sessions.remove(next.getId()) != null) {
						next.dispose();
					}
				}
			}
			break;
		case TargetDetachedFromTarget:
			DetachedFromTarget detached = (DetachedFromTarget) value;
			Session removed = null;
			if ((removed = sessions.remove(detached.getSessionId())) != null) {
				removed.dispose();
			}
			break;
		default:
			break;
		}
	}
}
